//
//  BusinessActivity.m
//  HappyStore
//
//  Created by 点点充 on 16/1/19.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "BusinessActivity.h"
#import "BusinessActCell.h"
#import "UsedTool.h"
#import "HeadPageView.h"
#import "BusinessActInfo.h"
#import "Release_ActivityChange.h"
@interface BusinessActivity ()
{
    NSMutableArray *_aryInfo;
    NSInteger paggge;
    
    NSMutableDictionary *muDicParameters;
    
    NSString *strProjectId;
    //视图头的图片
    NSArray *headImageAry;
    
    
    
}
@end

@implementation BusinessActivity

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16.f],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"商务活动";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"创建" style:UIBarButtonItemStylePlain target:self action:@selector(btnClickRight)];
    rightBar.tintColor = RGB(45, 45, 45);
    self.navigationItem.rightBarButtonItem = rightBar;
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    _aryInfo = [NSMutableArray array];
    paggge = 1;
    
    
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (_aryInfo.count != 0) {
            if ([[USER_DEFAULTS objectForKey:@"isOpenSound"] boolValue]) {//声音开关
                NSString *path = [[NSBundle mainBundle]pathForResource:@"refresh"
                                                                ofType:@"wav"];
                SystemSoundID soundID;
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
                AudioServicesPlaySystemSound(soundID); //仅播放音频
            }
            paggge = 1;
            [muDicParameters setObject:@"1" forKey:@"page"];
            [self startSearch];
        }else {
            [_mainTableView.mj_header endRefreshing];
        }
    }];
    
    
    
    _mainTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        paggge += 1;
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];
        [self startSearch];
    }];
    
    _mainTableView.mj_footer.hidden = YES;
    
    [[NSNotificationCenter defaultCenter]  addObserver:self
                                              selector:@selector(StartShaiXuanSearch:) name:@"StartShaiXuanBusinessActivity"
                                                object:nil];
    if (muDicParameters == nil) {
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:@"1" forKey:@"page"];
    }

    [self showRoundProgressWithTitle:@"请稍后..."];
    [self startSearch];
    
    self.mainSearchBar.layer.borderWidth = 1.f;
    self.mainSearchBar.layer.borderColor = [RGB(235, 235, 235) CGColor];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}

- (void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)StartShaiXuanSearch:(NSNotification *)dic
{
    muDicParameters = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];//通过这个获取到传递的对象
    _aryInfo = [NSMutableArray array];
    [self startSearch];
    
}

/**
 *  @author LLJ, 16-01-16 17:01:06
 *
 *  rightBarClick
 */
- (void)btnClickRight
{
    if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
        
        //取消显示后退键文字
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
        self.navigationItem.backBarButtonItem = barButtonItem;
        Release_ActivityChange *actVC = [[Release_ActivityChange alloc] initWithNibName:@"Release_ActivityChange" bundle:nil];
        [self.navigationController pushViewController:actVC animated:YES];
        
    }else{
        [SVProgressHUD showErrorWithStatus:@"请先登录!"];
        [SVProgressHUD dismissafterDelay:kHideHudDelay];
    }

}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    if (_aryInfo.count != 0) {
        _aryInfo = [NSMutableArray array];
        [_mainTableView reloadData];
    }
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    //NSLog(@"%@",searchBar.text);
    
    if (searchBar.text.length == 0) {
        return YES;
    }else {
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"title"];//类型
        [self startSearch];
        return YES;
    }
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //NSLog(@"-----%@",searchBar.text);
    if (searchBar.text.length != 0) {
        [searchBar resignFirstResponder];
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"title"];//类型
        [self startSearch];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:_aryInfo.count];
    return _aryInfo.count ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
        return 157;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        static NSString *cellSingle = @"BusinessCell";
        //注册
        UINib *nib = [UINib nibWithNibName:@"BusinessActCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellSingle];
        BusinessActCell *cell = [tableView dequeueReusableCellWithIdentifier:cellSingle forIndexPath:indexPath];
        if (!cell) {
            cell = [[BusinessActCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellSingle];
        }
    
        
        NSDictionary *dicData = [NSDictionary dictionaryWithDictionary:_aryInfo[indexPath.row]];
        
       
    [cell.photoImageView sd_setImageWithURL:[NSURL URLWithString:dicData[@"logo"]] placeholderImage:[UIImage imageNamed:@"img_normal3"]];
    cell.titleLabel.text = dicData[@"title"];
    cell.addressLabel.text = dicData[@"address"];
    //时间
    NSString *timeStr = dicData[@"createtime"];
    //年月日
    NSString *yearStr = [timeStr substringToIndex:10];
    //几点
    NSString *timeString = [timeStr substringWithRange:NSMakeRange(10,6)];
    //周几
    NSString *weekStr = [UsedTool getWeekDayForstring:timeStr];
    
    cell.timeLabel.text = [NSString stringWithFormat:@"%@ %@ %@",yearStr,weekStr,timeString];

//标签
    NSArray *arrayLabel = [dicData[@"lable"] componentsSeparatedByString:@","];
    if (arrayLabel.count>0) {
        
        cell.labelLabel.layer.borderWidth = 0.5f;
        cell.labelLabel.layer.borderColor = RGB(23, 176, 216).CGColor;
        cell.labelLabel.backgroundColor = RGB(217, 242, 255);
        cell.labelLabel.text = arrayLabel[0];
        CGSize size = [cell.labelLabel sizeThatFits:CGSizeMake(MAXFLOAT, 18)];
        cell.labelWidthConstraint.constant = size.width +10;
        
    }
    if (arrayLabel.count>1) {
        cell.labelLabelTwo.layer.borderWidth = 0.5f;
        cell.labelLabelTwo.layer.borderColor = RGB(23, 176, 216).CGColor;
        cell.labelLabelTwo.backgroundColor = RGB(217, 242, 255);
        cell.labelLabelTwo.text = arrayLabel[1];
        CGSize sizeTwo = [cell.labelLabelTwo sizeThatFits:CGSizeMake(MAXFLOAT, 18)];
        cell.labelWidthConstraintTwo.constant = sizeTwo.width +10;
    }
    if (arrayLabel.count==1) {
        cell.labelLabelTwo.text = @"";
        cell.labelWidthConstraintTwo.constant = 0;
    }
    
    
    return cell;
}

    
    



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
        
        //取消显示后退键文字
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
        
        self.navigationItem.backBarButtonItem = barButtonItem;
        
        BusinessActInfo *businessVC = [[BusinessActInfo alloc] init];
        businessVC.activityId = _aryInfo[indexPath.row][@"activityId"];
        [self.navigationController pushViewController:businessVC animated:YES];
        
//        strProjectId = _aryInfo[indexPath.row-1][@"activityId"];
//        
//        [self performSegueWithIdentifier:@"business_detail" sender:self];
        
    
    
    //
}

//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
//{
//    // segue.identifier：获取连线的ID
//    if ([segue.identifier isEqualToString:@"business_detail"]) {
//        BusinessActivity_Detail *result = segue.destinationViewController;
//        result.activityId = strProjectId;
//    }
//}


- (void)startSearch
{
    //page=页码&title=根据标题&industry=根据行业&money=-根据金额，格式（0-5000000 亿以上：1000000000-亿）&type=根据类型（个人，企业，政府）&address= 根据地区（格式：省-市-区 如果没有就：省-无-无）
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getActivity_app_activity.im"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        //banner数组
        headImageAry = [NSArray arrayWithArray:dicInfo[@"data"][@"banner"]];
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            if (paggge == 1) {
                [_mainTableView.mj_header endRefreshing];
                
                _aryInfo = [NSMutableArray arrayWithArray:[dicInfo objectForKey:@"data"][@"record"]];
                
                if (_aryInfo.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }else {
                [_mainTableView.mj_footer endRefreshing];
                NSArray *ary11 = [dicInfo objectForKey:@"data"][@"record"];
                for (int i = 0; i<ary11.count; i++) {
                    NSDictionary *dic1 = ary11[i];
                    [_aryInfo addObject:dic1];
                }
                if (ary11.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }
            
            
            [_mainTableView reloadData];
            [self hideBubble];
        }else {
            [_mainTableView reloadData];
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];
            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];

        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [_mainTableView.mj_header endRefreshing];
        [_mainTableView.mj_footer endRefreshing];
        [self showSingleIconBubble:error.localizedDescription];

    }];
}


@end
